﻿using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Traceability.API.Applications.Command.TracebackCommand;
using Traceability.Domain;
using Traceability.ErrorCode;
using Traceability.Infrastructure;
using Yitter.IdGenerator;

namespace Traceability.API.Applications.CommandHandler.TracebackCommandHandler
{
    public class TracebackAddCommandHandler : IRequestHandler<TracebackAddCommand, APIResult<int>>
    {

        private readonly IBaseRepository<Traceback_Information> _tracebackRepository;
        private readonly IMapper _mapper;

        public TracebackAddCommandHandler(IBaseRepository<Traceback_Information> tracebackRepository, IMapper mapper)
        {
            _tracebackRepository = tracebackRepository;
            _mapper = mapper;
        }

        public async Task<APIResult<int>> Handle(TracebackAddCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> aPIResult = new APIResult<int>();
            var res = _tracebackRepository.GetAll().AsNoTracking().Where(s => s.Batch == request.Batch);
            if(res.Any())
            {
                aPIResult.Code = EnumCode.File;
                aPIResult.Data = 0;
                aPIResult.Msg = "生产批次重复";
                return aPIResult;
            }



            var model = _mapper.Map<Traceback_Information>(request);
            model.SId = YitIdHelper.NextId();
            model.nformation_Completeness = 5;
            model.CreateUserId=request.CreateUserId;

            var count = await _tracebackRepository.Add(model);
            
            
            if (count>0)
            {
                aPIResult.Code = EnumCode.Ok;
                aPIResult.Data = count;
                aPIResult.Msg = "添加成功";
            }
            else
            {
                aPIResult.Code = EnumCode.File;
                aPIResult.Data = count;
                aPIResult.Msg = "添加失败";
            }

                return await Task.FromResult(aPIResult);

        }
    }
}
